package org.jeecg.config.mybatis;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.regex.Matcher;

/**
 * mybatis拦截器，自动注入创建人、创建时间、修改人、修改时间
 *
 * @Author scott
 * @Date 2019-01-19
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
		@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class MybatisInterceptor implements Interceptor {

	@Resource
	@Qualifier("history")
	private JdbcTemplate jdbcTemplate;

	// 封装了一下sql语句，使得结果返回完整xml路径下的sql语句节点id + sql语句
	public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId) {
		return showSql(configuration, boundSql);
	}

	// 进行？的替换
	public static String showSql(Configuration configuration, BoundSql boundSql) {
		// 获取参数
		Object parameterObject = boundSql.getParameterObject();
		List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
		// sql语句中多个空格都用一个空格代替
		String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
		if (!CollectionUtils.isEmpty(parameterMappings) && parameterObject != null) {
			// 获取类型处理器注册器，类型处理器的功能是进行java类型和数据库类型的转换
			TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
			// 如果根据parameterObject.getClass(）可以找到对应的类型，则替换
			if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
				sql = sql.replaceFirst("\\?",
						Matcher.quoteReplacement(getParameterValue(parameterObject)));
			} else {
				// MetaObject主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
				MetaObject metaObject = configuration.newMetaObject(parameterObject);
				for (ParameterMapping parameterMapping : parameterMappings) {
					String propertyName = parameterMapping.getProperty();
					if (metaObject.hasGetter(propertyName)) {
						Object obj = metaObject.getValue(propertyName);
						sql = sql.replaceFirst("\\?",
								Matcher.quoteReplacement(getParameterValue(obj)));
					} else if (boundSql.hasAdditionalParameter(propertyName)) {
						// 该分支是动态sql
						Object obj = boundSql.getAdditionalParameter(propertyName);
						sql = sql.replaceFirst("\\?",
								Matcher.quoteReplacement(getParameterValue(obj)));
					} else {
						// 打印出缺失，提醒该参数缺失并防止错位
						sql = sql.replaceFirst("\\?", "缺失");
					}
				}
			}
		}
		return sql;
	}

	private static String getParameterValue(Object obj) {
		String value = null;
		if (obj instanceof String) {
			value = "'" + obj.toString() + "'";
		} else if (obj instanceof Date) {
			DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT,
					DateFormat.DEFAULT, Locale.CHINA);
			if (StringUtils.isBlank(obj.toString())){
				value = "'" + formatter.format(new Date()) + "'";
			}else {
				value = "'" + formatter.format(obj) + "'";
			}
		} else {
			if (obj != null) {
				value = obj.toString();
			} else {
				value = "null";
			}
		}
		return value;
	}

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		String sqlId = mappedStatement.getId();
		log.debug("------sqlId------" + sqlId);
		String databaseId = mappedStatement.getDatabaseId();


		String peek1 = DynamicDataSourceContextHolder.peek();
		SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
		Object parameter = invocation.getArgs()[1];
		log.debug("------sqlCommandType------" + sqlCommandType);

		if (parameter == null) {
			return invocation.proceed();
		}

		if (SqlCommandType.INSERT == sqlCommandType) {
			LoginUser sysUser = this.getLoginUser();
			Field[] fields = oConvertUtils.getAllFields(parameter);
			for (Field field : fields) {
				log.debug("------field.name------" + field.getName());
				try {
					if ("username".equals(field.getName())) {
						field.setAccessible(true);
						Object localCreateBy = field.get(parameter);
						field.setAccessible(false);
						if (localCreateBy == null || "".equals(localCreateBy)) {
							if (sysUser != null) {
								// 登录人账号
								field.setAccessible(true);
								field.set(parameter, sysUser.getUsername());
								field.setAccessible(false);
							}
						}
					}
					// 注入创建时间
					if ("ctime".equals(field.getName()) || "createTime".equals(field.getName())) {
						field.setAccessible(true);
						Object localCreateDate = field.get(parameter);
						field.setAccessible(false);
						if (localCreateDate == null || "".equals(localCreateDate)) {
							field.setAccessible(true);
							field.set(parameter, new Date());
							field.setAccessible(false);
						}
					}
					//注入部门编码
//					if ("sysOrgCode".equals(field.getName())) {
//						field.setAccessible(true);
//						Object localSysOrgCode = field.get(parameter);
//						field.setAccessible(false);
//						if (localSysOrgCode == null || "".equals(localSysOrgCode)) {
//							// 获取登录用户信息
//							if (sysUser != null) {
//								field.setAccessible(true);
//								field.set(parameter, sysUser.getOrgCode());
//								field.setAccessible(false);
//							}
//						}
//					}
				} catch (Exception e) {
				}
			}
		}
//		if (SqlCommandType.UPDATE == sqlCommandType) {
//			LoginUser sysUser = this.getLoginUser();
//			Field[] fields = null;
//			if (parameter instanceof ParamMap) {
//				ParamMap<?> p = (ParamMap<?>) parameter;
//				//update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
//                String et = "et";
//				if (p.containsKey(et)) {
//					parameter = p.get(et);
//				} else {
//					parameter = p.get("param1");
//				}
//				//update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q-
//
//				//update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
//				if (parameter == null) {
//					return invocation.proceed();
//				}
//				//update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
//
//				fields = oConvertUtils.getAllFields(parameter);
//			} else {
//				fields = oConvertUtils.getAllFields(parameter);
//			}
//
//			for (Field field : fields) {
//				log.debug("------field.name------" + field.getName());
//				try {
//					if ("updateBy".equals(field.getName())) {
//						//获取登录用户信息
//						if (sysUser != null) {
//							// 登录账号
//							field.setAccessible(true);
//							field.set(parameter, sysUser.getUsername());
//							field.setAccessible(false);
//						}
//					}
//					if ("updateTime".equals(field.getName())) {
//						field.setAccessible(true);
//						field.set(parameter, new Date());
//						field.setAccessible(false);
//					}
//				} catch (Exception e) {
//					e.printStackTrace();
//				}
//			}
//		}
		// 获取节点的配置
		Configuration configuration = mappedStatement.getConfiguration();
		// 获取到最终的sql语句
		// BoundSql就是封装myBatis最终产生的sql类
		BoundSql boundSql = mappedStatement.getBoundSql(parameter);
		String sql = getSql(configuration, boundSql, sqlId);
		String peek = DynamicDataSourceContextHolder.peek();
		log.info("完整的sql:{}", sql);
		if (sqlId.contains("modules") || sqlId.contains("online")) {
			DynamicDataSourceContextHolder.push("master");
			log.info("--------------->>MybatisInterceptor原数据源{},切换数据源：{}", peek,DynamicDataSourceContextHolder.peek());
		} else {
			DynamicDataSourceContextHolder.push("history");
			log.info("--------------->>MybatisInterceptor原数据源{},切换数据源：{}", peek,DynamicDataSourceContextHolder.peek());
			addMesHis(sql);
			DynamicDataSourceContextHolder.push("business");
			log.info("--------------->>MybatisInterceptor原数据源{},切换数据源：{}", peek,DynamicDataSourceContextHolder.peek());
		}

		return invocation.proceed();
	}

	@DS("history")
	public void addMesHis(String sql) {
		jdbcTemplate.execute(sql);
		//DynamicDBUtil.update("mesHis",sql);
	}

	@Override
	public Object plugin(Object target) {
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
		// TODO Auto-generated method stub
	}

	//update-begin--Author:scott  Date:20191213 for：关于使用Quzrtz 开启线程任务， #465

	/**
	 * 获取登录用户
	 *
	 * @return
	 */
	private LoginUser getLoginUser() {
		LoginUser sysUser = null;
		try {
			sysUser = SecurityUtils.getSubject().getPrincipal() != null ? (LoginUser) SecurityUtils.getSubject().getPrincipal() : null;
		} catch (Exception e) {
			//e.printStackTrace();
			sysUser = null;
		}
		return sysUser;
	}
	//update-end--Author:scott  Date:20191213 for：关于使用Quzrtz 开启线程任务， #465

}
